﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace WenSkin.Controls
{
    [Designer(typeof(Design.Designer.WenDataTextBoxDesigner))]
    public class WenDataTextBox : WenControl
    {
        public WenDataTextBox() : base()
        {
            Size = new Size(300, 300);
            button = new WenButton("确定")
            {
                Location = new Point(238, 270),
                Size = new Size(60, 28),
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right,
                BorderStyle = WenButton.WenButtonBorderStyle.RoRectangle,
            };
            button.Click += (s, e) =>
            {
                OnButtonClick(e);
            };

            flow = new FlowLayoutPanel()
            {
                Location = new Point(1, 1),
                Size = new Size(298, 298),
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Left,
                AutoScroll = true,
            };

            this.Controls.Add(button);
            this.Controls.Add(flow);
        }

        #region 私有属性

        private FlowLayoutPanel flow;
        private WenButton button;
        private object dataSource;
        private WenDataTextBoxColumnTextCollection items;

        #endregion

        #region 公有属性

        //绑定数据
        [Browsable(false)]
        public object DataSource
        {
            get => dataSource;
            set
            {
                dataSource = value;
                switch (value)
                {
                    case DataRow dw:
                        DataBind(dw);
                        break;
                    case DataTable dt:
                        DataBind(dt.Rows[0]);
                        break;
                }
            }
        }

        [Category("Wen"), Description("获取或设置输入框列数据"), DefaultValue(null)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Editor(typeof(Design.Editor.WenCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public WenDataTextBoxColumnTextCollection Items => items ?? (items = new WenDataTextBoxColumnTextCollection(this));

        #region WenSql

        [Category("WenSql"), Description("获取或设置数据库名称"), DefaultValue(null)]
        public string DataTabaleName { get; set; }

        [Category("WenSql"), Description("获取插入数据库数据语句"), DefaultValue(null)]
        [Browsable(false)]
        public string InsertSqlString
        {
            get
            {
                string insertName = "";
                string insertValue = "";
                foreach (WenDataTextBoxColumnText ct in Items)
                {

                    if (!ct.Updater)
                        continue;
                    insertName += ct.ColumnName + ",";
                    insertValue += $"'{ct.Text}',";
                }
                insertName = insertName.Remove(insertName.Length - 1);
                insertValue = insertValue.Remove(insertValue.Length - 1);
                string sql = $"insert into {DataTabaleName} ({insertName}) Values({insertValue})";
                return sql;
            }
        }
        [Category("WenSql"), Description("获取更新数据库数据语句"), DefaultValue(null)]
        [Browsable(false)]
        public string UpdateSqlString
        {
            get
            {
                string setValue = "";
                WenDataTextBoxColumnText identityCloumn = null;
                foreach (WenDataTextBoxColumnText ct in Items)
                {
                    if (ct.Identity)
                    {
                        identityCloumn = ct;
                        continue;
                    }
                    if (!ct.Updater)
                        continue;

                    setValue += $"{ct.ColumnName}=N'{ct.Text}',";
                }
                setValue = setValue.Remove(setValue.Length - 1);


                //获取主键列

                if (identityCloumn == null)
                    return null;

                string whereValue = identityCloumn.Text.ToString();
                string sql = $"update {DataTabaleName} set {setValue} where {identityCloumn.ColumnName}='{whereValue}'";
                return sql;
            }
        }

        #endregion


        #endregion

        #region 委托
        [Category("Wen"), Description("确定按钮点击事件")]
        public event EventHandler ButtonClick;

        protected virtual void OnButtonClick(EventArgs e)
        {
            foreach (WenDataTextBoxColumnText ct in Items)
            {
                if (ct.AutoUpdaterDateTime)
                {
                    ct.Text = DateTime.Now.ToString();
                }
            }
            ButtonClick?.Invoke(this, e);
        }

        #endregion

        private void DataBind(DataRow dw)
        {
            foreach (DataColumn column in dw.Table.Columns)
            {
                WenDataTextBoxColumnText cloumnText = Items[column.ColumnName];
                if (cloumnText != null)
                    cloumnText.WenChoiceTextBox.Text = dw[column]?.ToString();
            }
        }

        #region 重绘

        protected override void WenOnPaint(Graphics g, Rectangle rec, PaintEventArgs e)
        {
            base.WenOnPaint(g, rec, e);
            using Pen pen = new Pen(Color.White);
            g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
        }

        #endregion

        #region 子类
        [ToolboxItem(false)]
        [DefaultProperty("TextLable")]
        [DesignTimeVisible(false)]
        public class WenDataTextBoxColumnText:Component
        {
            public WenDataTextBoxColumnText()
            {
                ReadOnly = false;
                Visible = true;
                Identity = false;
                Updater = true;
                AutoUpdaterDateTime = false;
            }

            public WenDataTextBoxColumnText(string text) : this()
            {
                TextLable = text;
            }

            #region 私有属性

            private bool identity;
            private string textLable;
            private string text;
            private bool readOnly;

            #endregion


            #region 公有属性   


            [Browsable(false)]
            public string Name { get; set; }

            [Category("WenInfo"), Description("显示文本"), DefaultValue(null)]
            public string Text
            {
                get => text;
                set { text = value; if (WenChoiceTextBox != null) WenChoiceTextBox.Text = value; }
            }

            [Category("WenInfo"), Description("数据列"), DefaultValue(null)]
            public string ColumnName { get; set; }
            [Category("WenInfo"), Description("数据列文本"), DefaultValue(null)]
            public string TextLable
            {
                get => textLable;
                set { textLable = value; if (WenChoiceTextBox != null) WenChoiceTextBox.TextLable = value; }
            }

            [Category("Wen设计"), Description("是否不允许编辑"), DefaultValue(false)]
            public bool ReadOnly
            {
                get => readOnly;
                set
                {
                    readOnly = value;
                    if (WenChoiceTextBox != null)
                        WenChoiceTextBox.ReadOnly = value;
                }
            }
            [Category("Wen设计"), Description("是否显示"), DefaultValue(true)]
            public bool Visible { get; set; }

            [Category("Wen设计"), Description("是否主键"), DefaultValue(false)]
            public bool Identity
            {
                get => identity; set
                {
                    identity = value;
                    if (value)
                    {
                        Updater = false;
                        ReadOnly = true;
                    }
                }
            }

            [Category("Wen设计"), Description("是否更新"), DefaultValue(true)]
            public bool Updater { get; set; }

            [Category("Wen设计"), Description("点击确定自动将内容更新为当前时间"), DefaultValue(false)]
            public bool AutoUpdaterDateTime { get; set; }

            [Browsable(false)]
            public WenLableTextBox WenChoiceTextBox { get; set; }

            #endregion
            public override string ToString()
            {
                return $"{ColumnName}[{TextLable}]";
            }
        }

        public class WenDataTextBoxColumnTextCollection : WenCollection
        {
            public WenDataTextBoxColumnTextCollection(WenDataTextBox owner)
            {
                this.owner = owner;
            }
            public WenDataTextBoxColumnText this[int index] { get => Items[index] as WenDataTextBoxColumnText; set => Items[index] = value; }
            public WenDataTextBoxColumnText this[string str]
            {
                get
                {
                    foreach (var item in Items)
                    {
                        if (item is WenDataTextBoxColumnText cloumnText)
                        {
                            if (cloumnText.ColumnName?.ToUpper() == str.ToUpper())
                                return cloumnText;
                        }
                    }
                    return null;
                }
            }
            #region 私有属性

            private WenDataTextBox owner { get; set; }

            #endregion

            public override int Add(object value)
            {
                if (value is WenDataTextBoxColumnText columnText)
                {
                    WenLableTextBox textBox = new WenLableTextBox()
                    {
                        TextLable = columnText.TextLable,
                        ReadOnly = columnText.ReadOnly,
                        Visible = columnText.Visible,
                        Width = 260,
                    };
                    textBox.TextChanged += (s, e) =>
                    {
                        columnText.Text = textBox.Text;
                        if (owner.dataSource is DataRow dw)
                        {
                            try
                            {
                                //Type type = dw.Table.Columns[columnText.ColumnName].DataType;
                                //dw[columnText.ColumnName] = new TypeConverter().ConvertTo(textBox.Text, type);
                                dw[columnText.ColumnName] = textBox.Text;
                            }
                            catch { }
                        }
                    };
                    columnText.WenChoiceTextBox = textBox;
                    owner.flow.Controls.Add(textBox);
                }
                return base.Add(value);
            }

            public override void Clear()
            {
                base.Clear();
                owner.flow.Controls.Clear();
            }
        }
        #endregion
    }
}
